#!/bin/sh
#
# webssh -- login the docker lab via web ssh
#
# Copyright (C) 2016-2020 Wu Zhangjin <lzufalcon@163.com>
#

uname | grep -q MINGW && PWD_OPT="-W"
TOP_DIR="$(cd "$(dirname "$0")"/../../ && pwd $PWD_OPT)"
. "$TOP_DIR/tools/docker/config" $* >/dev/null

docker ps -f name=$CONTAINER_NAME | grep -qv PORTS
[ $? -ne 0 ] && echo "LOG: $LAB_NAME is not running." && exit 1

WEBSSH_URL="$WEB_HTTP://${HOST}:${HOST_WEBSSH_PORT}?ssh=ssh://$UNIX_USER:$UNIX_PWD@$VNC_IP:$CONTAINER_SSH_PORT"

echo "LOG: Please login via ssh client with:"
echo
echo "    SSH_IP: $VNC_IP"
echo "  SSH_PORT: $CONTAINER_SSH_PORT"
echo "      User: $UNIX_USER"
echo "  Password: $UNIX_PWD"
echo "   Workdir: $LAB_WORKDIR/$CURRENT"
echo

echo "LOG: Or access via web browser:\n  $WEBSSH_URL"
echo

# Get web browser
get_browser
[ $? -ne 0 ] && echo "ERR: Give up browser launching for no web browser found" && exit 1

# Exit if running as root
[ `id -u` -eq 0 ] && echo "ERR: Web browsers can not run as root user, please run as normal user." && exit 1

(eval "'$__WEB_BROWSER'" "'$WEBSSH_URL'" >/dev/null 2>&1 &) >/dev/null 2>&1

if [ -n "$LOCALHOST" ]; then
    _WEBSSH_URL="$(echo "$WEBSSH_URL" | sed -e "s%localhost%$LOCALHOST%g" )"
    echo "LOG: Or access it outside via:\n  $_WEBSSH_URL"
    echo
fi
